import Core.Basic
from Core.package import *




class Worker_Thread(QThread):
    thread_task_data = Signal(dict)
    def __init__(self, parent = None):
        super().__init__(parent)
        self.driver = Core.Basic.GlobalVar.driver
        self.task_data = dict()
    
    def run(self):
        try:
            print("线程任务完成!")
              
        except Exception as e:
            print(f"提示 : 员工线程任务发生错误!\n\
                    错误信息: {e}")
        finally:
            self.thread_task_data.emit(self.task_data)
        
        
        
        # 线程任务完成，会自动发送信号的,无需手动发送,手动发送可能会导致发送两遍信号.
        # self.finished.emit()
    def __delattr__(self, name):
        print(f"提示 : 子任务子线程运行结束!正在销毁资源 {self}")
        return super().__delattr__(name)
    

class Staff_Scanf_Upload_Product_Script(QObject):
    Start_Task = Signal()   # 任务开始信号,启动任务时,请发送此信号
    Task_Finish = Signal()   # 任务完成信号,任务结束时候,请发送此信号
    Current_Completion_Process = Signal(int)
    Emergency_Stop = Signal()  # 紧急停止信号
    OnlyRun = Signal()  # 仅运行信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Start_Task.connect(self.RunTask)
        
    @Slot(str)
    def slot_fun(self,text):
        print(f"我是槽函数,我是 {text}")

    # 设置员工属性
    def Set_Staff_Attribute(self,**kwargs):
        """设置员工对象的属性，用于后续任务执行
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        print(f"已设置属性: {kwargs.keys()}")

    def RunTask(self):

        # 获取需要操作的 主线程 窗口的 UI 对象
        # 使用 self.parent() 获取父对象
        self.parent_widget = self.parent()
        if self.parent_widget is None:
            print(f"提示 : 父对象为空!\n请将创建员工对象时,将父对象作为参数传入!")
            return
        # 获取 任务按钮 UI 控件对象
        self.task_button_object_name = "pushButton_scanf_upload_product"
        self.task_button : QPushButton = self.parent().findChild(QPushButton,self.task_button_object_name)
        if self.task_button is None:
            print(f"提示 : 程序无法找到 {self.task_button_object_name} 对应的按钮!")
            print(f"提示 : 子任务结束!")
            return
        self.listwidget_object_name = "listWidget_upload_products"
        self.listwidget : QListWidget = self.parent().findChild(QListWidget,self.listwidget_object_name)
        if self.listwidget is None:
            print(f"提示 : 父对象中未找到 {self.listwidget_object_name} 对应的列表框!")
            print(f"提示 : 子任务结束!")
            return


        # # 创建子线程
        # self.workerthread = Worker_Thread()



        # # 绑定信号
        # self.workerthread.finished.connect(lambda : QMessageBox.information(self.parent_widget,"提示","任务完成!"))
        # self.workerthread.finished.connect(lambda : self.Task_Finish.emit())    # 子线程运行结束代表该员工类的任务结束
        # self.workerthread.finished.connect(lambda : self.workerthread.quit())   # 线程结束，销毁线程
        # self.workerthread.finished.connect(lambda : self.deleteLater())
        # self.workerthread.finished.connect(lambda : self.task_button.setEnabled(True))
        # self.workerthread.thread_task_data.connect(lambda task_data: print(task_data))


        # 启动子线程,开始执行任务
        self.task_button.setEnabled(False)
        self.listwidget.clear()
        
        
        Product_List_Directory = pathlib.Path("./Data/Product_Download_File").absolute().resolve()
        for item in pathlib.Path(Product_List_Directory).iterdir():

            widget = QWidget()
            lay = QHBoxLayout()
            widget.setLayout(lay)
            labe = QLabel(item.name)
            lay.addWidget(labe)
            
            if item.is_dir():
                TaoBao_Script_Path = item.joinpath("启动脚本-淘宝脚本.bat").absolute().resolve()
                Pdd_Script_Path = item.joinpath("启动脚本-拼多多脚本.bat").absolute().resolve()
                DouYin_Script_Path = item.joinpath("启动脚本-抖店脚本.bat").absolute().resolve()
                Script_Run_Path = item.absolute().resolve().__str__()
                
                if TaoBao_Script_Path.exists():
                    pushbutton = QPushButton("淘宝脚本")
                    # pushbutton.clicked.connect(lambda : subprocess.Popen(args=["start","",TaoBao_Script_Path], cwd=Script_Run_Path,shell=True))
                    pushbutton.clicked.connect(
                        lambda checked=False, tb_path=TaoBao_Script_Path, cwd=Script_Run_Path: 
                        subprocess.Popen(args=["start", "", tb_path], cwd=cwd, shell=True)
                    )
                    lay.addWidget(pushbutton)
                
                if Pdd_Script_Path.exists():
                    pushbutton = QPushButton("拼多多脚本")
                    # pushbutton.clicked.connect(lambda : subprocess.Popen(args=["start","",Pdd_Script_Path], cwd=Script_Run_Path,shell=True))
                    pushbutton.clicked.connect(
                        lambda checked=False, pdd_path=Pdd_Script_Path, cwd=Script_Run_Path: 
                        subprocess.Popen(args=["start", "", pdd_path], cwd=cwd, shell=True)
                    )
                    lay.addWidget(pushbutton)
                
                if DouYin_Script_Path.exists():
                    pushbutton = QPushButton("抖店脚本")
                    # pushbutton.clicked.connect(lambda : subprocess.Popen(args=["start","",Script_Run_Path], cwd=Script_Run_Path,shell=True))
                    pushbutton.clicked.connect(
                        lambda checked=False, dy_path=DouYin_Script_Path, cwd=Script_Run_Path: 
                        subprocess.Popen(args=["start", "", dy_path], cwd=cwd, shell=True)
                    )
                    lay.addWidget(pushbutton)

                
            
            listwidget_item = QListWidgetItem(self.listwidget)
            listwidget_item.setSizeHint(widget.sizeHint())
            self.listwidget.setItemWidget(listwidget_item, widget)
            
            self.task_button.setEnabled(True)
        
        # self.workerthread.start()
        

        


















if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    # 编写 控制台 程序
    staff = Staff_Scanf_Upload_Product_Script(app)
    staff.RunTask()
    
    sys.exit(app.exec_())